const mysql = require('mysql')
let pools = {}
//回调方式 koa 没法使用，留在这里仅作参考
let query = (sql, callback,host = '127.0.0.1') => {
    if (!pools.hasOwnProperty(host)) {
        pools[host] = mysql.createPool({
            host: host,
            port: '3306',
            user: 'root',
            password: '123456',
            database: 'test20180217'
        })
    }

    pools[host].getConnection((err, connection) => {
        connection.query(sql, (err, results) => {
            callback(err, results)
            connection.release()
        })
    })
}

mysqlConfig = require("./config").mysqlConfig
function query2(sql,obj, host = '127.0.0.1') {
    if (!pools.hasOwnProperty(host)) {
        pools[host] = mysql.createPool(
/*             {
            host: host,
            port: '3306',
            user: 'root',
            password: '123456',
            database: 'test20180217'
        } */
        mysqlConfig
        )
    }



    return new Promise((resolve, reject) => {
        pools[host].getConnection((err, connection) => {
            console.log("sql ======")
            console.log(sql)
            console.log(obj)
            connection.query(sql, obj,(err, results) => {
                if (err)
                    reject(err)
                else
                    resolve(results)

                connection.release()
            })
        })
    })

}

//仅测试 mysql 连接可用性
function testMysql() {
    return new Promise((resolve, reject) => {
        const mysql = require('mysql');

        const connection = mysql.createConnection({
            host: 'localhost',
            user: 'root',
            password: '123456',
            database: 'test20180217'
        });

        connection.on('error', function () {
            //console.error('createConnection 请正确启动 mysql 服务器');
            reject('createConnection 请正确启动 mysql 服务器');
        })

        //这里是实际连接动作，如果没有启动 mysql，会在这里 reject
        connection.connect(function (err) {
            if (err) {
                //console.error('error connecting: ' + err.stack);
                reject('error connecting: ' + err.stack);
            }
            //connect 正确,验证一个简单查询
            else {
                //console.log('connected as id ' + connection.threadId)
                connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
                    if (error) {
                        reject('[Connect ERROR] - ', error.message);
                    }

                    resolve(results);
                    //结束前关闭 connection
                    connection.end();
                })
            }
        })
    })
}

module.exports = {
    query2,
    query,
    testMysql
}